package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问卷列表
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2021-11-5 12:36:23
 */
@Controller
@RequestMapping("/module/feed")
public class FeedController extends BaseController {
    @Resource
    private FeedService feedService;
    @Resource
    private GroupsService groupsService;
    @Resource
    private DeviceNodeService deviceNodeService;
    @Resource
    private DeviceService deviceService;

    @Log("查询饲料页面")
    @GetMapping()
    @RequiresPermissions("module:feed:feed")
    String temperatureLimit(Model model) {
        List<Groups> groups = groupsService.list();
        model.addAttribute("groups", groups);
        UserDO userDO = getUser();
        if(userDO.getUserType() > 1) {//集团用户
//            qw.eq("jituan_id", userDO.getGroupId());
            model.addAttribute("groupId", userDO.getGroupId());
        }
        return "module/feed/index";
    }

    @Log("查询饲料列表数据")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:feed:feed")
    public DataTableLayUI<Feed> list(DataTableLayUI<Feed> condition) {

        DataTableLayUI<Feed> dt = feedService.pageSearchLayUI(condition);
        List<Feed> list = dt.getData();
        for (Feed t : list){
            Groups groups = groupsService.findById(t.getGroupId());
            if (groups != null){
                t.setGroupName(groups.getGroupName());
            }
        }
        return dt;
    }


    @Log("新增饲料页面")
    @GetMapping("/add")
    @RequiresPermissions("module:feed:add")
    String add(Model model) {
        Feed feed = new Feed();
        model.addAttribute("feed", feed);
        List<Groups> groups = groupsService.list();
        model.addAttribute("groups", groups);
        UserDO userDO = getUser();
        if(userDO.getUserType() > 1) {//集团用户
//            qw.eq("jituan_id", userDO.getGroupId());
            model.addAttribute("groupId", userDO.getGroupId());
        }
        return "module/feed/detail";
    }


    @Log("编辑饲料页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:feed:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        Feed feed = feedService.findById(id);
        model.addAttribute("feed", feed);
        List<Groups> groups = groupsService.list();
        model.addAttribute("groups", groups);
        UserDO userDO = getUser();
        if(userDO.getUserType() > 1) {//集团用户
//            qw.eq("jituan_id", userDO.getGroupId());
            model.addAttribute("groupId", userDO.getGroupId());
        }
        return "module/feed/detail";
    }

    /**
     * 保存
     */
    @Log("新增饲料")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:feed:add")
    public R save(@Valid Feed feed) {
        if (feedService.save(feed)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新饲料")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:feed:edit")
    public R update(@Valid Feed feed) {
        Feed hisFeed = feedService.findById(feed.getId());
        // 修改了温度
        if (feed.getHighTemperature().doubleValue() != hisFeed.getHighTemperature().doubleValue() || feed.getLowTemperature().doubleValue() != hisFeed.getLowTemperature().doubleValue()){
            QueryWrapper<DeviceNode> nodeQueryWrapper = new QueryWrapper<>();
            nodeQueryWrapper.eq("feed_id", feed.getId());


            List<DeviceNode> deviceNodes = deviceNodeService.list(nodeQueryWrapper);
            for (DeviceNode deviceNode : deviceNodes){
                Device device = deviceService.findById(deviceNode.getDeviceId());
                if (device.getWarningTimeInterval() != null){
                    LocalDateTime now = LocalDateTime.now();
                    // 减去分钟,使温度报警在一分钟后
                    LocalDateTime calMinutes = now.minus(Duration.ofMinutes(device.getWarningTimeInterval() - 1));
                    Date date = Date.from(calMinutes.atZone(ZoneId.systemDefault()).toInstant());
                    deviceNode.setLastWarnTime(date);
                    deviceNodeService.updateById(deviceNode);
                }

            }
        }
        feedService.updateById(feed);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除饲料")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:feed:remove")
    public R remove( Integer id) {
        if (feedService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    @Log("切换饲料")
    @PostMapping("/changeFeed")
    @ResponseBody
    R changeFeed(@RequestParam Map<String,Object> paramJson) {
        JSONObject jsonRequest = JSONUtil.parseObj(paramJson);
        int node_id = jsonRequest.containsKey("nodeId") ? jsonRequest.getInt("nodeId") : 0;
        int feed_id = jsonRequest.containsKey("feedId") ? jsonRequest.getInt("feedId") : 0;
        Feed feed = feedService.findById(feed_id);
        if (feed == null){
            return R.error();
        }
        String feed_name = feed.getFeedName();
        if(feed_id == -1){ //清空
            UpdateWrapper<DeviceNode> nodeUpdateWrapper = new UpdateWrapper<>();
            nodeUpdateWrapper.eq("id", node_id);
            nodeUpdateWrapper.set("feed_id", null);
            nodeUpdateWrapper.set("feed_name", null);
            deviceNodeService.update(nodeUpdateWrapper);
        }else {
            UpdateWrapper<DeviceNode> nodeUpdateWrapper = new UpdateWrapper<>();
            nodeUpdateWrapper.eq("id", node_id);
            nodeUpdateWrapper.set("feed_id", feed_id);
            nodeUpdateWrapper.set("feed_name", feed_name);
            nodeUpdateWrapper.set("ignor_time",  DateUtils.getAfterDateMinute(5));
            deviceNodeService.update(nodeUpdateWrapper);
        }
        return R.ok();
    }
}
